<template>
  <div>
    <el-page-header @back="goBack"> </el-page-header>

    <div class="createPage">
      <el-form
        label-width="80px"
        ref="userInAppMan"
        :model="form"
        :rules="rules"
        style="padding-left: 20px"
      >
        <div class="title">基本信息</div>
        <el-form-item label="" style="margin-top: 34px">
          <el-upload
            accept=".png,.jpg,.jpeg"
            :show-file-list="false"
            action="/merchantApi/oss/upload"
            :headers="{
              auth_token: getToken(),
              auth_tmp: curTmp,
              auth_tck: curTck,
            }"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
          >
            <div class="uploadImg" v-if="imageUrl">
              <img :src="imageUrl" alt="" />
            </div>
            <div class="uploadImg" v-else>
              <img :src="require('@/assets/imgs/geren/info3.png')" alt="" />
            </div>
            <div>上传头像</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入姓名"
            style="width: 604px"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="username">
          <el-input
            :disabled="this.$route.query.id ? true : false"
            v-model="form.username"
            placeholder="请输入邮箱"
            style="width: 604px"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input
          :disabled="this.$route.query.id ? true : false"
            v-model="form.mobile"
            placeholder="请输入手机号"
            style="width: 604px"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="form.roleId"
            placeholder="请选择角色"
            style="width: 604px"
          >
            <el-option
              v-for="val of roleList"
              :key="val.id"
              :label="val.name"
              :value="val.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!$route.query.id">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            style="width: 604px"
            show-password
            :maxlength="32"
          ></el-input>
        </el-form-item>

        <!-- <div class="title" style="margin: 40px 0">权限管理</div>
        <el-form-item label="">
            <div v-for="(item, i) of menuList" :key="i">
            <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" @change="handleCheckAllChange($event,i)">商户管理</el-checkbox>
            <el-checkbox-group v-model="item.checkedCities" @change="handleCheckedCitiesChange($event,i)" style="margin-left: 24px">
                <el-checkbox v-for="city in item.children" :label="city.label" :key="city.label">{{city.label}}</el-checkbox>
            </el-checkbox-group>
        </div>
        </el-form-item> -->
        <el-form-item label="" style="margin-top: 60px">
          <el-button class="width120" @click="goBack">取消</el-button>
          <el-button class="width120" type="primary" @click="save"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  isMobile,
  isPassword,
  isPerson,
  regPassNum,
  isEmail,
} from "@/utils/validate";
// import md5 from "js-md5";
import crypto from "@/crypto";
import { randomWord } from "@/utils/getRandom";
import { getToken, getUserInfo } from "@/utils/public";
import { mapMutations } from "vuex";

export default {
  name: "settingCreateUser",
  data() {
    const checkRealName = (rule, value, callback) => {
      if (!isPerson(value)) {
        callback(new Error("格式有误"));
      } else {
        callback();
      }
    };
    const checkPhone = (rule, value, callback) => {
      if (isMobile(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的手机号码"));
      }
    };
    const checkEmail = (rule, value, callback) => {
      if (isEmail(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的邮箱"));
      }
    };
    const checkPassword = (rule, value, callback) => {
      if (value.indexOf(" ") > 0) {
        callback(new Error("只能包含数字、大写字母、小写字母或特殊符号"));
      }
      if (value.length < 8 || value.length > 32) {
        callback(new Error("密码长度8-32个字符"));
      }
      if (isPassword(value)) {
        callback(new Error("只能包含数字、大写字母、小写字母或特殊符号"));
      }
      if (regPassNum(value) !== 3 && regPassNum(value) !== 4) {
        callback(new Error("数字、大写字母、小写字母和特殊符号至少包含3种"));
      } else {
        callback();
      }
    };
    return {
      curTmp: null,
      curTck: null,
      len: [8, 9, 10, 11, 12][
        Math.floor(Math.random() * [8, 9, 10, 11, 12].length)
      ],
      imageUrl: "",
      form: {},
      headUrl: "",
      rules: {
        realName: [
          { required: true, message: "请输入姓名", trigger: "change" },
          {
            pattern: /^(?!\s+).*(?<!\s)$/,
            message: "格式有误",
            trigger: "change",
          },
          { validator: checkRealName, trigger: "change" },
        ],
        username: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          { validator: checkEmail, trigger: "change" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "change" },
          { validator: checkPhone, trigger: "change" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { validator: checkPassword, trigger: "change" },
        ],
      },
      roleList: [],
      // checkAll: false,
      // checkedCities: ["子商户概览"],
      // cities: ["子商户概览", "子商户管理", "添加子商户"],
      // menuList: [],
      // isIndeterminate: true,
    };
  },
  created() {
    this.curTmp = new Date().getTime();
    this.curTck = crypto.set(
      getToken() + "_" + this.curTmp + "_" + randomWord(this.len),
      "a1g0qoalvv19aed3"
    );

    this.$http.post("/role/all").then((res) => {
      if (res.code === "0000") {
        this.roleList = res.data;
      }
    });
    const id = this.$route.query.id;
    if (id) {
      this.id = id;
      this.$http
        .get("/sys/user/get", {
          params: { id },
        })
        .then((res) => {
          if (res.code === "0000") {
            this.form = {
              realName: res.data.realName,
              mobile: res.data.mobile,
              username: res.data.username,
              roleId: res.data.roleId,
              headUrl: res.data.headUrl,
            };
            if (res.data.headUrl) {
              this.getImgInfo(res.data.headUrl);
            }
          }
        });
    }
  },
  watch: {
    "$store.state.testLine": {
      handler() {
        if (this.$route.name == this.$options.name) {
          this.$http.post("/role/all").then((res) => {
            if (res.code === "0000") {
              this.roleList = res.data;
            }
          });
          const id = this.$route.query.id;
          if (id) {
            this.id = id;
            this.$http
              .get("/sys/user/get", {
                params: { id },
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.form = {
                    realName: res.data.realName,
                    mobile: res.data.mobile,
                    username: res.data.username,
                    roleId: res.data.roleId,
                    headUrl: res.data.headUrl,
                  };
                  if (res.data.headUrl) {
                    this.getImgInfo(res.data.headUrl);
                  }
                }
              });
          }
        }
      },
    },
    deep: true,
  },
  methods: {
    ...mapMutations(["changeLive"]),
    getToken,
    // handleCheckAllChange(val, i) {
    //   console.log(val, i);
    //   this.menuList[i].checkedCities = val
    //     ? this.menuList[i].children.map((v) => v.label)
    //     : [];
    //   this.menuList[i].isIndeterminate = false;
    // },
    // handleCheckedCitiesChange(value, i) {
    //   console.log(value);
    //   let checkedCount = value.length;
    //   this.menuList[i].checkAll =
    //     checkedCount === this.menuList[i].children.length;
    //   this.menuList[i].isIndeterminate =
    //     checkedCount > 0 && checkedCount < this.menuList[i].children.length;
    // },
    beforeUpload(file) {
      const is2M = file.size / 1024 / 1024 < 2;
      const type = ["image/jpeg", "image/jpg", "image/png"].includes(file.type);

      if (!type) {
        this.$message.warning("上传图片只支持jpeg、jpg、png格式");
        return false;
      }
      if (!is2M) {
        this.$message.warning("上传图片大小不能超过2M");
        return false;
      }
      return true;
    },
    getImgInfo(id) {
      this.imageUrl = window.location.origin + `/merchantApi/oss/view?id=${id}`;
    },
    handleSuccess(res, file) {
      this.form.headUrl = res.data.id;
      this.imageUrl = "";
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    goBack() {
      this.$backTo(`/setting/userManagement`);
    },
    save() {
      this.$refs.userInAppMan.validate((valid) => {
        if (valid) {
          const info = getUserInfo();
          if (this.id) {
            this.$http
              .post("/sys/user/update", {
                ...this.form,
                userType: info.userType.includes("main")
                  ? "main_user"
                  : "sub_user",
                status: 1,
                id: this.id,
                appIds: [this.$store.state.appId],
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("修改成功！");
                  this.testCancel();
                  // this.goBack();
                }
              });
          } else {
            this.$http
              .post("/sys/user/save", {
                ...this.form,
                userType: info.userType.includes("main")
                  ? "main_user"
                  : "sub_user",
                status: 1,
                appIds: [this.$store.state.appId],
                password: crypto.set(this.form.password),
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("新增成功！");
                  this.testCancel();
                  // this.goBack();
                }
              });
          }
        }
      });
    },
    testCancel() {
      this.$store.commit("changeLive", false);
      setTimeout(() => {
        this.$store.commit("changeLive", true);
      }, 0);
      this.$backTo("/setting/userManagement");
    },
  },
};
</script>

<style lang="scss" scoped>
.createPage {
  background: #fff;
  padding: 34px 0 37px 34px;
  color: #666;
  min-width: 1200px;
  .title {
    color: #4f595f;
    position: relative;
    font-size: 24px;
    font-weight: 600;
    margin-left: -20px;
    &::before {
      content: "";
      width: 4px;
      height: 24px;
      background: #03bfc6;
      position: absolute;
      left: -34px;
      top: 7px;
    }
  }
  .uploadImg {
    width: 102px;
    height: 102px;
    background: #fafafa;
    // border: 1px solid #bfbfbf;
    border-radius: 50%;
    color: #869daa;
    font-size: 28px;
    text-align: center;
    line-height: 102px;
    margin-bottom: 10px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
